import axios from "axios";
import { ElMessage } from "element-plus";
const baseURL = "http://127.0.0.1:8088/api/v1";
import router from "@/router";

const instance = axios.create({
  baseURL, // 所有的请求地址前缀部分
  timeout: 60000, // 请求超时时间毫秒
  headers: {
    // 设置后端需要的传参类型
    "Content-Type": "application/json",
  },
});

instance.interceptors.request.use(
  (config) => {
    const token = sessionStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    console.log(error);
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      if (Object.prototype.hasOwnProperty.call(response.data, "code")) {
        if (response.data.code === 0) {
          return Promise.resolve(response.data);
        }
        ElMessage({
          showClose: true,
          message: response.data.message || "操作失败!!!",
          type: "error",
        });
        return Promise.reject(response);
      }
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    // 对请求错误做些什么
    console.log(error);
    if (error && error.response && error.response.status === 403) {
      ElMessage.error("无访问权限");
      router.push({
        path: "/login",
      });
    }
    return Promise.reject(error);
  }
);

export default instance;
